// +----------------------------------------------------------------------
// | CodeEngine
// +----------------------------------------------------------------------
// | Copyright 艾邦
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: TaoGe <liangtao.gz@foxmail.com>
// +----------------------------------------------------------------------
// | Version: 2.0 2019/7/11 15:22
// +----------------------------------------------------------------------
'use strict';

import CryptoJS from "crypto-js";

/**
 * 辅助工具类
 */
export default class Tool {

	static salt = 'cxNZsJAfXgwsuURG';

	static key( key ) {
		const string = Tool.salt + String( key );
		return CryptoJS.MD5( string ).toString().toUpperCase();
	}

	// 编码
	static encode( value ) {
		const src = CryptoJS.enc.Utf8.parse( value );
		const base64string = CryptoJS.enc.Base64.stringify( src );
		return base64string.toString();
	}

	// 解码
	static decode( value ) {
		const base64string = CryptoJS.enc.Base64.parse( value );
		return CryptoJS.enc.Utf8.stringify( base64string );
	}

	// 校验是否为空
	static empty( value ) {
		if ( typeof ( value ) === 'undefined' ) {
			return true
		} else if ( value === null ) {
			return true
		} else if ( typeof ( value ) === 'string' && this.trim( value ) === '' ) {
			return true
		} else if ( typeof ( value ) === 'object' && ( JSON.stringify( value ) === '{}' || JSON.stringify( value ) === '[]' ) ) {
			return true
		}
		return false
	}

	// 删除空格
	static trim( value ) {
		return String( value ).replace( /(^\s*)|(\s*$)/g, '' )
	}

	// 小数填零
	static prefixInteger( num, n ) {
		return ( Array( n ).join( '0' ) + num ).slice( -n );
	}

	// 四舍五入保留2位小数（不够位数，则用0替补）
	static keepTwoDecimalFull( num ) {
		let result = parseFloat( num );
		if ( isNaN( result ) ) {
			return 0;
		}
		result = Math.round( num * 100 ) / 100;
		let s_x = result.toString();
		let pos_decimal = s_x.indexOf( '.' );
		if ( pos_decimal < 0 ) {
			pos_decimal = s_x.length;
			s_x += '.';
		}
		while ( s_x.length <= pos_decimal + 2 ) {
			s_x += '0';
		}
		return Number( s_x );
	}

	// API回调方法
	static cb( response = {}, callback = {} ) {
		let state;
		// 默认回调方法
		const call = Object.assign( {
			success: function ( res ) {
			},
			fail: function ( res ) {
			},
			complete: function ( res ) {
			}
		}, callback );
		if ( typeof response === 'object' && response !== null ) {
			if ( response.status && String( response.status ).toLowerCase() === 'ok' ) {
				call.success( response );
				state = true;
			} else {
				call.fail( response );
				state = false;
			}
			call.complete( response );
		}
		return state;
	}

	// 排序函数
	static ksort( obj ) {
		if ( typeof ( obj ) === 'object' && obj !== null ) {
			let newkey = Object.keys( obj ).sort();
			// 先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
			let newObj = {};// 创建一个新的对象，用于存放排好序的键值对
			for ( let i = 0; i < newkey.length; i++ ) { // 遍历newkey数组
				// 向新创建的对象中按照排好的顺序依次增加键值对
				if ( typeof ( obj[ newkey[ i ] ] ) === 'object' && obj[ newkey[ i ] ] !== null ) {
					newObj[ newkey[ i ] ] = this.ksort( obj[ newkey[ i ] ] )
				} else {
					newObj[ newkey[ i ] ] = obj[ newkey[ i ] ]
				}
			}
			return newObj // 返回排好序的新对象
		} else {
			return obj
		}
	}

	// 生成指定长度唯一值
	static uuid( len = 8, radix = 16 ) {
		let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
		let uuid = [];
		let i;
		radix = radix || chars.length;
		if ( len ) {
			for ( i = 0; i < len; i++ ) uuid[ i ] = chars[ 0 | Math.random() * radix ]
		} else {
			let r;
			uuid[ 8 ] = uuid[ 13 ] = uuid[ 18 ] = uuid[ 23 ] = '-';
			uuid[ 14 ] = '4';
			for ( i = 0; i < 36; i++ ) {
				if ( !uuid[ i ] ) {
					r = 0 | Math.random() * 16;
					uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ]
				}
			}
		}
		return uuid.join( '' );
	}

	// 生成标准GUID
	static guid() {
		return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace( /[xy]/g, function ( c ) {
			let r = Math.random() * 16 | 0;
			let v = c === 'x' ? r : ( r & 0x3 | 0x8 );
			return v.toString( 16 );
		} )
	}

	// 网址中提取域名
	static domainName( url = '' ) {
		const sign = '://';
		let pos = url.indexOf( sign );
		// 如果以协议名开头
		// 如：http://github.com/
		if ( pos >= 0 ) {
			pos += sign.length;
			// 截取协议名以后的部分
			// github.com/
			url = url.slice( pos )
		}
		// 以/作分割
		const array = url.split( '/' );
		return array[ 0 ]
	}

	// 系统返回数据状态
	static errorCodeThrow( response ) {
		let { code, msg } = response;
		switch ( code ) {
			case 40000 :
				break;
			case 40001 :
				break;
			case 40002 :
				break;
			case 40003 :
				break;
			case 40004 :
				break;
			case 40005 :
				break;
			case 40006 :
				break;
			case 40007 :
				break;
			case 40008 :
				break;
			default:
		}
		throw new Error( msg );
	}


	// // RSA非对称分段加密
	// static rsaEncrypt( data ) {
	// 	const encrypt = new JSEncrypt();
	// 	encrypt.setPublicKey( config.service.rsa_cert.public_key );
	// 	return encrypt.encrypt( data );
	// }
	//
	// // RSA非对称分段解密
	// static rsaDecrypt( data ) {
	// 	const encrypt = new JSEncrypt();
	// 	encrypt.setPublicKey( config.service.rsa_cert.private_key );
	// 	return encrypt.decrypt( data )
	// }
}
